<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <BasicTable @register="registerTable" @selection-change="selectionChange">
      <template #toolbar>
        <a-button @click.stop="add" type="primary" v-auth="'PublicStamp:add'">{{
          t('新增')
        }}</a-button>
        <a-button @click="setEnabled" type="primary" v-auth="'PublicStamp:disable'">{{
          enabledTitle
        }}</a-button>
        <a-button
          v-if="stampInfo.type == StampType.PRIVATE_SIGNATURE"
          @click.stop="setDefault"
          type="primary"
          v-auth="'PublicStamp:defaultStamp'"
          >{{ t('设置默认签章') }}</a-button
        >
        <span v-if="stampInfo.type == StampType.PUBLIC_SIGNATURE && userName == 'admin'">
          <SelectUser
            style="display: inline"
            :visible="stampInfo.id ? true : false"
            :selectedIds="maintainIds"
            :multiple="true"
            @change="designated"
          >
            <a-button
              type="primary"
              @click="checkSingleRow"
              v-auth="'PublicStamp:designMaintainPersonnel'"
              >{{ t('指定维护人员') }}
            </a-button>
          </SelectUser>
        </span>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:user-add-outlined',
              auth: 'PublicStamp:addPeople',
              disabled: isDisabled(record.maintain),
              onClick: handleAddUser.bind(null, record),
              ifShow: stampInfo.type == StampType.PUBLIC_SIGNATURE,
            },
            {
              icon: 'clarity:note-edit-line',
              auth: 'PublicStamp:edit',
              disabled: isDisabled(record.maintain),
              onClick: edit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              auth: 'PublicStamp:delete',
              color: 'error',
              disabled: isDisabled(record.maintain),
              popConfirm: {
                title: t('是否确认删除'),
                confirm: handleDelete.bind(null, record.id),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <StampDetail
      v-if="stampInfo.visible"
      :info="stampInfo.info"
      :type="stampInfo.type"
      :id="stampInfo.id"
      @close="close"
    />
    <SelectMember
      v-if="visible"
      :visible="visible"
      :multiple="true"
      :selectedIds="selectedUserIds"
      @close="
        () => {
          visible = false;
        }
      "
      @change="handleUserpost"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import StampDetail from './components/stamp/StampInfo.vue';
  import {
    getStampList,
    deleteStamp,
    EnabledStamp,
    setDefaultStamp,
    addMaintain,
    getStampMember,
    addMember,
  } from '/@/api/workflow/stamp';
  import { StampInfo } from '/@/api/workflow/model';

  import { SelectUser, SelectMember } from '/@/components/SelectOrganizational/index';
  import { StampType } from '/@/enums/workflowEnum';
  import { useRouter } from 'vue-router';
  import { notification, Switch, Tag, Image } from 'ant-design-vue';

  import { ref, onMounted, computed, reactive, h } from 'vue';
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';

  import { PageWrapper } from '/@/components/Page';
  import { useUserStore } from '/@/store/modules/user';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const configColumns: BasicColumn[] = [
    {
      title: t('签章名字'),
      dataIndex: 'name',
      width: 180,
      align: 'left',
      sorter: {
        multiple: 1,
      },
    },
    {
      title: t('签章分类'),
      dataIndex: 'stampCategoryName',
      width: 160,
      align: 'left',
      sorter: {
        multiple: 2,
      },
    },
    {
      title: t('图片'),
      dataIndex: 'fileUrl',
      width: 160,
      align: 'left',
      customRender: ({ record }) => {
        return h(Image, {
          src: record.fileUrl,
          width: '60px',
          height: '22px',
        });
      },
    },
    {
      title: t('状态'),
      dataIndex: 'enabledMark',
      width: 120,
      sorter: {
        multiple: 3,
      },
      customRender: ({ record }) => {
        return h(Switch, {
          checked: record.enabledMark === 1,
          checkedChildren: t('已启用'),
          unCheckedChildren: t('已禁用'),
        });
      },
    },
    {
      title: t('默认签章'),
      dataIndex: 'isDefault',
      width: 120,
      align: 'left',
      customRender: ({ record }) => {
        return record.isDefault == 1 ? h(Tag, { color: 'processing' }, () => t('默认')) : h('div');
      },
    },
    {
      title: t('备注'),
      align: 'left',
      dataIndex: 'remark',
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: t('关键字'),
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
  ];
  const visible = ref<boolean>(false);
  const selectedUserIds = ref<string[]>([]);
  const userStore = useUserStore();
  const title = computed(() => {
    return stampInfo.type == StampType.PRIVATE_SIGNATURE ? t('电子签章列表') : t('公共签章列表');
  });
  const actionColumn = computed(() => {
    return {
      width: stampInfo.type == StampType.PRIVATE_SIGNATURE ? 80 : 120,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    };
  });
  const userName = computed(() => {
    return userStore.getUserInfo.userName;
  });

  let stampInfo: {
    type: StampType;
    id: string;
    visible: boolean;
    info: StampInfo | undefined;
  } = reactive({
    id: '',
    info: undefined,
    visible: false,
    type: StampType.PRIVATE_SIGNATURE,
  });
  const [registerTable, { reload, getSelectRows, clearSelectedRowKeys, setColumns, setProps }] =
    useTable({
      title: title,
      api: getStampList,
      rowKey: 'id',
      columns: [],
      formConfig: {
        rowProps: {
          gutter: 16,
        },
        schemas: searchFormSchema,
      },
      rowSelection: {
        type: 'radio',
      },
      beforeFetch: (params) => {
        //发送请求默认新增  左边树结构所选区域id
        return { ...params, stampType: stampInfo.type };
      },
      striped: false,
      useSearchForm: true,
      showTableSetting: true,
    });
  onMounted(async () => {
    const { currentRoute } = useRouter();
    stampInfo.type =
      currentRoute.value.name == 'PublicStamp'
        ? StampType.PUBLIC_SIGNATURE
        : StampType.PRIVATE_SIGNATURE;
    let column = configColumns;
    if (currentRoute.value.name == 'PublicStamp') {
      column = column.filter((o) => {
        return o.dataIndex != 'isDefault';
      });
    }
    setProps({
      actionColumn: actionColumn.value,
    });
    setColumns(column);
  });

  const maintainIds = ref<string[]>([]);
  const enabledTitle = ref<string>(t('启用'));

  function isDisabled(ids) {
    if (stampInfo.type == 1) {
      let arr = ids ? ids.split(',') : [];
      return userName.value == 'admin' ? false : !arr.includes(userStore.getUserInfo.id);
    } else {
      return false;
    }
  }

  function selectionChange({ keys, rows }) {
    if (keys?.length > 0) {
      enabledTitle.value = rows[0].enabledMark === 1 ? t('禁用') : t('启用');
    } else {
      enabledTitle.value = t('启用');
    }
  }

  function add() {
    stampInfo.id = '';
    stampInfo.info = undefined;
    stampInfo.visible = true;
  }
  function edit(row: StampInfo) {
    if (row.id) stampInfo.id = row.id;
    stampInfo.info = row;
    stampInfo.visible = true;
  }
  function close() {
    stampInfo.visible = false;

    reload();
  }
  async function handleDelete(id: string) {
    try {
      let res = await deleteStamp([id]);
      save(res, t('删除'));
    } catch (error) {}
    reload();
  }
  async function setEnabled() {
    let rows = warning();
    if (!rows) {
      return;
    }

    try {
      let res = await EnabledStamp(rows.id);
      save(res, enabledTitle.value);
      clearSelectedRowKeys();
    } catch (error) {}
    reload();
  }
  async function setDefault() {
    let rows = warning();
    if (!rows) {
      return;
    }
    try {
      let res = await setDefaultStamp(rows.id);
      save(res, t('默认签章'));
      clearSelectedRowKeys();
    } catch (error) {}
    reload();
  }

  async function designated(ids) {
    try {
      let res = await addMaintain(stampInfo.id, ids);
      save(res, t('指定维护人员'));
      clearSelectedRowKeys();
    } catch (error) {}
    reload();
  }
  function save(res: boolean, title: string) {
    if (res) {
      notification.open({
        type: 'success',
        message: title,
        description: t('成功'),
      });
    } else {
      notification.open({
        type: 'error',
        message: title,
        description: t('失败'),
      });
    }
  }
  function checkSingleRow() {
    let rows = warning();

    if (rows) {
      stampInfo.id = rows.id;
      maintainIds.value = rows.maintain ? rows.maintain.split(',') : [];
    } else {
      stampInfo.id = '';
      maintainIds.value = [];
    }
  }
  function warning() {
    const selectRows = getSelectRows();
    if (selectRows.length === 0) {
      notification.warning({
        message: t('警告'),
        description: t('必须选中一行！'),
      }); //提示消息
      return false;
    } else {
      return selectRows[0];
    }
  }
  function handleAddUser(record: Recordable) {
    stampInfo.id = record.id;
    getStampMember(record.id).then((res) => {
      selectedUserIds.value = res.map((it) => {
        return it.id;
      });
      visible.value = true;
    });
  }
  function handleUserpost(v) {
    addMember(stampInfo.id, v).then(() => {
      notification.success({
        message: t('添加成员成功'),
        description: t('成功'),
      });
    });
  }
</script>
